// Fill out your copyright notice in the Description page of Project Settings.


#include "EventActor.h"

AEventActor::AEventActor()
{
 	PrimaryActorTick.bCanEverTick = true;
	_hoverToRotate = false;

	// The mesh
	_mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
	SetRootComponent(_mesh);

	static ConstructorHelpers::FObjectFinder<UStaticMesh> cubeAsset(
		TEXT("StaticMesh'/Game/StarterContent/Shapes/Shape_Cube.Shape_Cube'"));
	if (cubeAsset.Succeeded())
	{
		_mesh->SetStaticMesh(cubeAsset.Object);
		_mesh->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f));
	}

	_mesh->OnBeginCursorOver.AddDynamic(this, &AEventActor::OnHoverBegin);
	_mesh->OnEndCursorOver.AddDynamic(this, &AEventActor::OnHoverEnd);
	_mesh->OnClicked.AddDynamic(this, &AEventActor::OnClicked);
	
	// The box
	_box = CreateDefaultSubobject<UBoxComponent>(TEXT("TriggerBox"));
	_box->SetRelativeLocation(FVector(0.0f, 0.0f, 150.0f));
	_box->SetBoxExtent(FVector(50.0, 50.0, 50.0));
	_box->SetupAttachment(_mesh);

	_box->OnComponentBeginOverlap.AddDynamic(this, &AEventActor::OnOverlapBegin);
	_box->OnComponentEndOverlap.AddDynamic(this, &AEventActor::OnOverlapEnd);
}

void AEventActor::BeginPlay()
{
	Super::BeginPlay();

	FBox bb = GetComponentsBoundingBox(false, true);
	DrawDebugBox(GetWorld(), bb.GetCenter(), bb.GetExtent(), FColor::Yellow, true);

	APlayerController* playerCtrl = GetWorld()->GetFirstPlayerController();
	playerCtrl->bShowMouseCursor = true;
	playerCtrl->bEnableClickEvents = true;
	playerCtrl->bEnableMouseOverEvents = true;
}

void AEventActor::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (_hoverToRotate)
	{
		FRotator rotation = GetActorRotation();
		rotation.Yaw += DeltaTime * 20.0f;
		SetActorRotation(rotation);
	}
}

void AEventActor::OnOverlapBegin(class UPrimitiveComponent* comp, class AActor* otherActor,
								 class UPrimitiveComponent* otherComp, int32 otherBodyIndex,
								 bool fromSweep, const FHitResult& sweepResult)
{
	UE_LOG(LogTemp, Warning, TEXT("Overlap begin with %s"), *otherActor->GetName());
}

void AEventActor::OnOverlapEnd(class UPrimitiveComponent* comp, class AActor* otherActor,
							   class UPrimitiveComponent* otherComp, int32 otherBodyIndex)
{
	UE_LOG(LogTemp, Warning, TEXT("Overlap end with %s"), *otherActor->GetName());
}

void AEventActor::OnHoverBegin(class UPrimitiveComponent* comp)
{
	UE_LOG(LogTemp, Warning, TEXT("Mouse hover begin"));
	_hoverToRotate = true;
}

void AEventActor::OnHoverEnd(class UPrimitiveComponent* comp)
{
	UE_LOG(LogTemp, Warning, TEXT("Mouse hover end"));
	_hoverToRotate = false;
}

void AEventActor::OnClicked(class UPrimitiveComponent* comp, FKey key)
{
	UE_LOG(LogTemp, Warning, TEXT("Mouse clicked: %s"), *key.ToString());

	FRotator rotation(0.0, 0.0, 0.0);
	SetActorRotation(rotation);
	_hoverToRotate = false;
}
